{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 第17章 潜在语义分析"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 习题17.1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "&emsp;&emsp;试将图17.1的例子进行潜在语义分析，并对结果进行观察。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<br/><center>\n",
    "<img src=\"./images/17-1-word-text-matrix.png\" style=\"zoom: 50%;\"><br/><div style=\"color:orange; border-bottom: 1px solid #d9d9d9;display: inline-block;color: #000;padding: 2px;\">图17.1 单词-文本矩阵例</div></center>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答思路：**\n",
    "\n",
    "1. 给出潜在语义分析算法\n",
    "2. 使用`numpy`的奇异值分解方法对图17.1的例子进行潜在语义分析\n",
    "3. 对结果进行观察及分析"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：潜在语义分析算法**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第17.2节的潜在语义分析算法的计算步骤：\n",
    "\n",
    "> 1. 单词-文本矩阵  \n",
    "> 给定文本集合$D=\\{d_1,d_2,\\cdots,d_n\\}$和单词集合$W=\\{w_1, w_2, \\cdots, w_m\\}$。潜在语义分析首先将这些数据表示成一个单词-文本矩阵\n",
    "> \n",
    "> $$ X= \\left[ \\begin{array}{cccc} \n",
    "x_{11} & x_{12} & \\cdots & x_{1n} \\\\\n",
    "x_{21} & x_{22} & \\cdots & x_{2n} \\\\\n",
    "\\cdots & \\cdots & \\cdots & \\cdots \\\\\n",
    "x_{m1} & x_{m2} & \\cdots & x_{mn}\n",
    "\\end{array}\\right] $$\n",
    "> \n",
    "> 其中，元素$x_{ij}$表示单词$w_i$在文本$d_j$中出现的频数或权值。\n",
    "> \n",
    "> 2. 截断奇异值分解  \n",
    "> 根据确定的话题个数$k$对单词-文本矩阵$X$进行截断奇异值分解\n",
    "> \n",
    "> $$ X \\approx U_k \\Sigma_k V_k^T = [u_1 \\ u_2 \\ \\cdots \\ u_k]\n",
    "\\left[ \\begin{array}{cccc} \n",
    "\\sigma_1 & 0 & 0 & 0 \\\\\n",
    "0 & \\sigma_2 & 0 & 0 \\\\\n",
    "0 & 0 & \\ddots & 0 \\\\\n",
    "0 & 0 & 0 & \\sigma_k\n",
    "\\end{array} \\right]\\left[ \\begin{array}{c} \n",
    "v_1^T \\\\ v_2^T \\\\ \\vdots \\\\ v_k^T \n",
    "\\end{array} \\right] $$\n",
    "> \n",
    "> 其中$k \\leqslant n \\leqslant m$，$U_k$是$m \\times k$矩阵，它的列由$X$的前$k$个相互正交的左奇异向量组成，$\\Sigma_k$是$k$阶对角方阵，对角元素为前$k$个最大奇异值，$V_k$是$n \\times k$矩阵，它的列由$X$的前$k$个相互正交的右奇异向量组成。\n",
    "> \n",
    "> 3. 话题向量空间  \n",
    "> 矩阵$U_k$的每一个列向量$u_1,u_2,\\cdots,u_k$表示一个话题，称为话题向量。由这$k$个话题向量张成一个子空间\n",
    "> \n",
    "> $$ U_k = [u_1 \\ u_2 \\ \\cdots \\ u_k] $$\n",
    "> 称为话题向量空间。\n",
    "> \n",
    "> 4. 文本的话题空间表示  \n",
    "> 矩阵$X$的第$j$列向量$x_j$满足\n",
    "> \n",
    "> $$ x_j \\approx \\sum_{l=i}^k \\sigma_l v_{jl} u_l, \\quad j=1,2,\\cdots,n $$\n",
    ">\n",
    "> &emsp;&emsp;综上，可以通过对单位-文本矩阵的奇异值分解进行潜在语义分析\n",
    "> \n",
    "> $$ X \\approx U_k \\Sigma_k V_k^T = U_k (\\Sigma_k V_k^T) $$\n",
    "> \n",
    "> 得到话题空间$U_k$，以及文本在话题空间的表示$(\\Sigma_k V_k^T)$。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：对图17.1的例子进行潜在语义分析**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "\n",
    "def lsa_svd(X, k):\n",
    "    \"\"\"\n",
    "    潜在语义分析的矩阵奇异值分解\n",
    "    :param X: 单词-文本矩阵\n",
    "    :param k: 话题数\n",
    "    :return: 话题向量空间、文本集合在话题向量空间的表示\n",
    "    \"\"\"\n",
    "    # 单词-文本矩阵X的奇异值分解\n",
    "    U, S, V = np.linalg.svd(X)\n",
    "    # 矩阵的截断奇异值分解，取前k个\n",
    "    U = U[:, :k]\n",
    "    S = np.diag(S[:k])\n",
    "    V = V[:k, :]\n",
    "\n",
    "    return U, np.dot(S, V)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "话题空间U：\n",
      "[[-0.08  0.28  0.89]\n",
      " [-0.16  0.57 -0.45]\n",
      " [-0.14 -0.01  0.  ]\n",
      " [-0.73 -0.55  0.  ]\n",
      " [-0.15 -0.18  0.  ]\n",
      " [-0.63  0.51 -0.  ]]\n",
      "文本在话题空间的表示SV：\n",
      "[[-0.79 -1.57 -2.86 -2.96]\n",
      " [ 1.08  2.15 -0.1  -1.33]\n",
      " [ 1.79 -0.89  0.    0.  ]]\n"
     ]
    }
   ],
   "source": [
    "X = np.array([[2, 0, 0, 0],\n",
    "              [0, 2, 0, 0],\n",
    "              [0, 0, 1, 0],\n",
    "              [0, 0, 2, 3],\n",
    "              [0, 0, 0, 1],\n",
    "              [1, 2, 2, 1]])\n",
    "\n",
    "# 设置精度为2\n",
    "np.set_printoptions(precision=2, suppress=True)\n",
    "# 假设话题的个数是3个\n",
    "U, SV = lsa_svd(X, k=3)\n",
    "print(\"话题空间U：\")\n",
    "print(U)\n",
    "print(\"文本在话题空间的表示SV：\")\n",
    "print(SV)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第3步：对结果进行观察及分析**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;在假设话题个数为3的情况下，单词`airplane`在话题3上的权值最大为0.89，表示单词`airplane`在话题3中的重要度最高；文本$d_2$在话题2中的权值最大为2.15，表示话题2在文本$d_2$中的重要度最高。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题17.2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;给出损失函数是散度损失时的非负矩阵分解（潜在语义分析）的算法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答思路：**  \n",
    "1. 给出散度的定义\n",
    "2. 给出散度损失的定义\n",
    "3. 给出损失函数是平方损失时的非负矩阵分解算法\n",
    "4. 写出损失函数是散度损失时的非负矩阵分解算法\n",
    "5. 自编程实现损失函数是散度损失时的非负矩阵分解算法"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：散度的定义**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中附录E的KL散度的定义：\n",
    "\n",
    "> &emsp;&emsp;KL散度是描述两个概率分布$Q(x)$和$P(x)$相似度的一种度量，记作$D(Q\\|P)$。对离散随机变量，KL散度定义为\n",
    "> $$ D(Q\\|P) = \\sum_i Q(i) \\log \\frac{Q(i)}{P(i)} \\tag{E.1} $$\n",
    "> 对连续随机变量，KL散度定义为\n",
    "> $$ D(Q\\|P) = \\int Q(x) \\log \\frac{Q(x)}{P(x)} dx \\tag{E.2} $$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：散度损失的定义**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第17章的定理17.2：\n",
    "\n",
    "> **定理17.2** 散度损失$D(X \\| WH)$对下列乘法更新规则\n",
    "> $$ H_{lj} \\leftarrow H_{lj} \\frac{\\displaystyle \\sum_i [W_{il} X_{ij} / (WH)_{ij}]}{\\displaystyle \\sum_i W_{il}} \\\\\n",
    "W_{il} \\leftarrow W_{il} \\frac{\\displaystyle \\sum_j [H_{lj} X_{ij} / (WH)_{ij}]}{\\displaystyle \\sum_j H_{lj}} $$\n",
    "> 是非增的。当且仅当$W$和$H$是散度损失函数的稳定点时，函数的更新不变。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第3步：损失函数是平方损失时的非负矩阵分解算法**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第17章的算法17.1的非负矩阵分解的迭代算法\n",
    "\n",
    "> **算法17.1 （非负矩阵分解的迭代算法）**    \n",
    "> 输入：单词-文本矩阵$X \\geqslant 0$，文本集合的话题个数$k$，最大迭代次数$t$；  \n",
    "> 输出：话题矩阵$W$，文本表示矩阵$H$。  \n",
    "> （1）初始化  \n",
    "> &emsp;&emsp;$W \\geqslant 0$，并对$W$的每一列数据归一化；$H \\geqslant 0$。  \n",
    "> （2）迭代  \n",
    "> &emsp;&emsp;对迭代次数由1到$t$执行下列步骤：  \n",
    "> &emsp;&emsp;（a）更新$W$的元素，对$l$从1到$k$，$i$从1到$m$按照如下公式更新$W_{il}$\n",
    "> $$ W_{il} = W_{il} \\frac{(XH^T)_{il}}{(WHH^T)_{il}}, \\quad i=1,2,\\cdots,m; \\quad l=1,2,\\cdots,k $$\n",
    "> &emsp;&emsp;（b）更新$H$的元素，对$l$从1到$k$，$j$从1到$n$按照如下公式更新$H_{lj}$\n",
    "> $$ H_{lj} = H_{lj} \\frac{(W^TX)_{lj}}{(W^TWH)_{lj}}, \\quad l=1,2,\\cdots,k; \\quad j=1,2,\\cdots,n $$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第4步：损失函数是散度损失时的非负矩阵分解算法**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输入：单词-文本矩阵$X \\geqslant 0$，文本集合的话题个数$k$，最大迭代次数$t$；  \n",
    "输出：话题矩阵$W$，文本表示矩阵$H$。  \n",
    "（1）初始化  \n",
    "&emsp;&emsp;$W \\geqslant 0$，并对$W$的每一列数据归一化；  \n",
    "&emsp;&emsp;$H \\geqslant 0$；  \n",
    "（2）迭代  \n",
    "&emsp;&emsp;对迭代次数由1到$t$执行下列步骤：  \n",
    "&emsp;&emsp;（a）更新$W$的元素，对$l$从1到$k$，$i$从1到$m$按照如下公式更新$W_{il}$\n",
    "$$\n",
    "W_{il} \\leftarrow W_{il} \\frac{\\displaystyle \\sum_j [H_{lj} X_{ij}/ (WH)_{ij}]}{\\displaystyle \\sum_j H_{lj}}\n",
    "$$  \n",
    "&emsp;&emsp;（b）更新$H$的元素，对$l$从1到$k$，$j$从1到$n$按照如下公式更新$H_{lj}$\n",
    "$$\n",
    "H_{lj} \\leftarrow H_{lj} \\frac{\\displaystyle \\sum_i [W_{il} X_{ij}/ (WH)_{ij}]}{\\displaystyle \\sum_i W_{il}}\n",
    "$$\n",
    "&emsp;&emsp;（c）计算损失函数\n",
    "$$\n",
    "\\sum_{i=0}^m \\sum_{j=0}^n  \\left( X_{ij} \\log \\frac{X_{ij}}{(WH)_{ij}} - X_{ij} + (WH)_{ij} \\right)\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第5步：自编程实现损失函数是散度损失时的非负矩阵分解算法**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "\n",
    "class DivergenceNmfLsa:\n",
    "    def __init__(self, max_iter=1000, tol=1e-6, random_state=0):\n",
    "        \"\"\"\n",
    "        损失函数是散度损失时的非负矩阵分解\n",
    "        :param max_iter: 最大迭代次数\n",
    "        :param tol: 容差\n",
    "        :param random_state: 随机种子\n",
    "        \"\"\"\n",
    "        self.max_iter = max_iter\n",
    "        self.tol = tol\n",
    "        self.random_state = random_state\n",
    "        np.random.seed(self.random_state)\n",
    "\n",
    "    def _init_param(self, X, k):\n",
    "        self.__m, self.__n = X.shape\n",
    "        self.__W = np.random.random((self.__m, k))\n",
    "        self.__H = np.random.random((k, self.__n))\n",
    "\n",
    "    def _div_loss(self, X, W, H):\n",
    "        Y = np.dot(W, H)\n",
    "        loss = 0\n",
    "        for i in range(self.__m):\n",
    "            for j in range(self.__n):\n",
    "                loss += (X[i][j] * np.log(X[i][j] / Y[i][j]) if X[i][j] * Y[i][j] > 0 else 0) - X[i][j] + Y[i][j]\n",
    "\n",
    "        return loss\n",
    "\n",
    "    def fit(self, X, k):\n",
    "        \"\"\"\n",
    "        :param X: 单词-文本矩阵\n",
    "        :param k: 话题个数\n",
    "        :return:\n",
    "        \"\"\"\n",
    "        # (1)初始化\n",
    "        self._init_param(X, k)\n",
    "        # (2.c)计算散度损失\n",
    "        loss = self._div_loss(X, self.__W, self.__H)\n",
    "\n",
    "        for _ in range(self.max_iter):\n",
    "            # (2.a)更新W的元素\n",
    "            WH = np.dot(self.__W, self.__H)\n",
    "            for i in range(self.__m):\n",
    "                for l in range(k):\n",
    "                    s1 = sum(self.__H[l][j] * X[i][j] / WH[i][j] for j in range(self.__n))\n",
    "                    s2 = sum(self.__H[l][j] for j in range(self.__n))\n",
    "                    self.__W[i][l] *= s1 / s2\n",
    "\n",
    "            # (2.b)更新H的元素\n",
    "            WH = np.dot(self.__W, self.__H)\n",
    "            for l in range(k):\n",
    "                for j in range(self.__n):\n",
    "                    s1 = sum(self.__W[i][l] * X[i][j] / WH[i][j] for i in range(self.__m))\n",
    "                    s2 = sum(self.__W[i][l] for i in range(self.__m))\n",
    "                    self.__H[l][j] *= s1 / s2\n",
    "\n",
    "            new_loss = self._div_loss(X, self.__W, self.__H)\n",
    "            if abs(new_loss - loss) < self.tol:\n",
    "                break\n",
    "\n",
    "            loss = new_loss\n",
    "\n",
    "        return self.__W, self.__H"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "话题空间W：\n",
      "[[0.   0.   1.39]\n",
      " [0.   1.47 0.  ]\n",
      " [0.35 0.   0.  ]\n",
      " [1.77 0.   0.  ]\n",
      " [0.35 0.   0.  ]\n",
      " [1.06 1.47 0.7 ]]\n",
      "文本在话题空间的表示H：\n",
      "[[0.   0.   1.41 1.41]\n",
      " [0.   1.36 0.   0.  ]\n",
      " [1.44 0.   0.   0.  ]]\n"
     ]
    }
   ],
   "source": [
    "X = np.array([[2, 0, 0, 0],\n",
    "              [0, 2, 0, 0],\n",
    "              [0, 0, 1, 0],\n",
    "              [0, 0, 2, 3],\n",
    "              [0, 0, 0, 1],\n",
    "              [1, 2, 2, 1]])\n",
    "\n",
    "# 设置精度为2\n",
    "np.set_printoptions(precision=2, suppress=True)\n",
    "# 假设话题的个数是3个\n",
    "k = 3\n",
    "div_nmf = DivergenceNmfLsa(max_iter=1000, random_state=2022)\n",
    "W, H = div_nmf.fit(X, k)\n",
    "print(\"话题空间W：\")\n",
    "print(W)\n",
    "print(\"文本在话题空间的表示H：\")\n",
    "print(H)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题17.3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;给出潜在语义分析的两种算法的计算复杂度，包括奇异值分解法和非负矩阵分解法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答思路：**  \n",
    "1. 给出潜在语义分析的奇异值分解法，并计算复杂度\n",
    "2. 给出潜在语义分析的非负矩阵分解法，并计算复杂度"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;给定文本集合$D=\\{d_1,d_2,\\cdots,d_n\\}$和单词集合$W=\\{w_1, w_2, \\cdots, w_m\\}$，则单词-文本矩阵为$$\n",
    "X= \\left[ \\begin{array}{cccc} \n",
    "x_{11} & x_{12} & \\cdots & x_{1n} \\\\\n",
    "x_{21} & x_{22} & \\cdots & x_{2n} \\\\\n",
    "\\cdots & \\cdots & \\cdots & \\cdots \\\\\n",
    "x_{m1} & x_{m2} & \\cdots & x_{mn}\n",
    "\\end{array}\\right]\n",
    "$$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：计算潜在语义分析的奇异值分解法的复杂度**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "奇异值分解法（含截断奇异值分解）的复杂度分析：  \n",
    "\n",
    "1. 求行空间和零空间标准正交基，其复杂度是$O(nm^2)$  \n",
    "2. 对$XX^T$进行特征值分解，其复杂度是$O(m^3)$  \n",
    "\n",
    "可知，总复杂度为$O(nm^2) + O(m^3)$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：计算潜在语义分析的非负矩阵分解法的复杂度**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于非负矩阵分解是迭代的，假设迭代次数为$t$：\n",
    "\n",
    "- 损失函数是平方损失时的非负矩阵分解的复杂度\n",
    "    1. 迭代次数从1到$t$次，复杂度包含$t$因子\n",
    "    2. 更新$W$的元素，复杂度为$O(km)$\n",
    "    3. 更新$H$的元素，复杂度为$O(kn)$\n",
    "\n",
    "  可知，复杂度为$O(tkm)+O(tkn)$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 损失函数是散度损失时的非负矩阵分解的复杂度\n",
    "    1. 迭代次数从1到$t$次，复杂度包含$t$因子\n",
    "    2. 更新$W$的元素，复杂度为$O(km)$\n",
    "    3. 更新$H$的元素，复杂度为$O(kn)$\n",
    "    4. 计算损失函数，复杂度为$O(mn)$\n",
    "\n",
    "  可知，复杂度为$O(tkm)+O(tkn)+O(tmn)$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 习题17.4\n",
    "&emsp;&emsp;列出潜在语义分析与主成分分析的异同。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答：**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答思路：**  \n",
    "1. 给出主成分分析的定义\n",
    "2. 给出潜在语义分析的定义\n",
    "3. 写出两者的相同点\n",
    "4. 写出两者的不同点"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**解答步骤：**   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第1步：主成分分析的定义**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第16章的主成分分析介绍：\n",
    "\n",
    "> &emsp;&emsp;主成分分析（PCA）是一种常用的无监督学习方法，这一方法利用正交变换把由线性相关变量表示的观测数据转换为少数几个由线性无关变量表示的数据，线性无关的变量称为主成分。主成分分析属于降维方法。主成分分析主要用于发现数据中的基本结构，即数据中变量之间的关系，是数据分析的有力工具，也用于其他机器学习方法的前处理。主成分分析属于多元统计分析的经典方法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第16章的本章概要的主成分分析方法：\n",
    "\n",
    "> &emsp;&emsp;主成分分析方法主要有两种，可以通过相关矩阵的特征值分解或样本矩阵的奇异值分解进行。  \n",
    "> &emsp;&emsp;（1）相关矩阵的特征值分解算法。针对$m \\times n$样本矩阵$X$，求样本相关矩阵\n",
    "> $$ R = \\frac{1}{n-1}XX^T $$\n",
    "> 再求样本相关矩阵的$k$个特征值和对应的单位特征向量，构造正交矩阵\n",
    "> $$ V = (v_1, v_2, \\cdots, v_k) $$\n",
    "> $V$的每一列对应一个主成分，得到$k \\times n$样本主成分矩阵\n",
    "> $$ Y = V^TX $$\n",
    "> &emsp;&emsp;（2）矩阵$X$的奇异值分解算法。针对$m \\times n$样本矩阵$X$\n",
    "> $$ X' = \\frac{1}{\\sqrt{n-1}}X^T $$\n",
    "> 对矩阵$X'$进行截断奇异值分解，保留$k$个奇异值、奇异向量，得到\n",
    "> $$ X' = USV^T $$\n",
    "> V的每一列对应一个主成分，得到$k \\times n$样本主成分矩阵$Y$\n",
    "> $$ Y = V^T X $$"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第2步：潜在语义分析的定义**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;根据书中第17章的潜在语义分析介绍：\n",
    "\n",
    "> &emsp;&emsp;潜在语义分析（LSA）是一个无监督学习方法，主要用于文本的话题分析，其特点是通过矩阵分解发现文本与单词之间的基于话题的语义关系。潜在语义分析使用的是非概率的话题分析模型，关键是对单词-文本矩阵进行矩阵因子分解（话题分析）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "&emsp;&emsp;算法部分详见书中第17.2节的潜在语义分析算法的计算步骤。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第3步：两者的相同点**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. 两者都属于无监督学习方法\n",
    "2. 两者都基于矩阵的奇异值分解\n",
    "3. 两者都可采用截断奇异值分解\n",
    "3. 两者都可用于降维"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**第4步：两者的不同点**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. PCA对数据矩阵的协方差矩阵或者相关系数矩阵进行奇异值分解，而LSA直接对数据矩阵进行奇异值分解\n",
    "2. PCA需要对数据进行正规化，而LSA可以不对数据进行正规化\n",
    "3. PCA的原始矩阵一般不是稀疏矩阵，而LSA的矩阵一般是稀疏矩阵"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "c50c7698ff25eb1d7dce4c52e3d5cc14b3b23d6a97d4fb70aad8c815eba6f63e"
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "273.188px"
   },
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
